<template>
	<div class="login-page">
		<!-- Element Plus 登录表单 -->
		<div class="mx-auto" style="max-width: 460px; margin-top: 100px">
			<h2 class="font-bold mx-auto text-center" style="margin-bottom: 10px">后台管理登录</h2>
			<el-form class="w-full" :model="loginForm" :rules="loginRules">
				<el-form-item prop="username">
					<el-input v-model="loginForm.username" placeholder="请输入用户名" />
				</el-form-item>
				<el-form-item prop="password">
					<el-input v-model="loginForm.password" type="password" placeholder="请输入密码" />
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="d_login" class="w-full">登录</el-button>
				</el-form-item>
			</el-form>
		</div>
	</div>
</template>

<script name="LoginPage" lang="ts" setup>
import md5 from 'md5';

const router = useRouter();

const loginForm = reactive({
	username: '',
	password: '',
});
const loginRules = {
	username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
	password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
};

const login = () => {
	$fetch('/api/admin/user/login', {
		method: 'POST',
		body: { ...loginForm, password: md5(loginForm.password) },
	})
		.then((res: any): void => {
			if (res.code === 1) {
				ElMessage.success(res.message);
				router.replace('/admin');
			} else {
				ElMessage.error(res.message);
			}
		})
		.catch((err: any) => {
			ElMessage.error(err.message);
		});
};
const d_login = useDebounce(login, 500);
</script>
